// Copyright © 2023 Cisco Systems, Inc. and its affiliates.
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package findingkey

import (
	"fmt"

	apitypes "github.com/openclarity/openclarity/api/types"
	"github.com/openclarity/openclarity/core/to"
)

type MalwareKey struct {
	MalwareName string
	MalwareType string
	Path        string
	RuleName    string
}

// String returns an unique string representation of the malware finding.
func (k MalwareKey) String() string {
	return fmt.Sprintf("%s.%s.%s.%s", k.MalwareName, k.MalwareType, k.Path, k.RuleName)
}

// MalwareString returns an unique string representation of the malware independent of
// where the malware finding was found by the scanner.
func (k MalwareKey) MalwareString() string {
	return fmt.Sprintf("%s.%s.%s", k.MalwareName, k.MalwareType, k.RuleName)
}

// Filter returns a string that can be used to filter the malware finding in the database.
func (k MalwareKey) Filter() string {
	return fmt.Sprintf(
		"findingInfo/malwareName eq '%s' and findingInfo/malwareType eq '%s' and findingInfo/path eq '%s' and findingInfo/ruleName eq '%s'",
		k.MalwareName, k.MalwareType, k.Path, k.RuleName,
	)
}

func GenerateMalwareKey(info apitypes.MalwareFindingInfo) MalwareKey {
	return MalwareKey{
		MalwareName: to.ValueOrZero(info.MalwareName),
		MalwareType: to.ValueOrZero(info.MalwareType),
		Path:        to.ValueOrZero(info.Path),
		RuleName:    to.ValueOrZero(info.RuleName),
	}
}
